package com.huawei.fakedouyin.manager;

import android.content.Context;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.Build;
import android.provider.MediaStore;
import android.util.LruCache;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;

import com.huawei.fakedouyin.base.BaseApplication;
import com.huawei.fakedouyin.data.DmItem;
import com.huawei.fakedouyin.data.VideoInfo;
import com.huawei.fakedouyin.util.LiveDataSet;
import com.huawei.fakedouyin.util.LogUtilKt;
import com.huawei.fakedouyin.util.MainExecutor;
import com.huawei.fakedouyin.util.ScreenUtilKt;
import com.huawei.fakedouyin.util.ViewUtil;
import com.huawei.fakedouyin.view.MyVideoView;
import com.huawei.faketaobao.http.BaseResult;
import com.huawei.faketaobao.http.FakeRepository;

import java.io.IOException;
import java.util.HashMap;

import kotlin.coroutines.Continuation;
import kotlin.coroutines.CoroutineContext;
import kotlin.coroutines.EmptyCoroutineContext;


/**
 * 视频播放 弹幕播放 管理类
 */
public class PlayManager {

    static PlayManager playManager;

    private MyVideoView myVideoView;
    //缓存封面图
    private LruCache<String, Bitmap> lruCache;
    //保存视频信息
    private HashMap<String, VideoInfo> videoInfoHashMap;
    public int contentWidth, contentHeight = 0;
    //是否初始化
    public boolean isInit = false;
    //正在播放的视频信息
    public VideoInfo usingInfo = null;

    public static PlayManager getInstance() {
        if (playManager == null) {
            synchronized (PlayManager.class) {
                playManager = new PlayManager();
                long maxMemory = Runtime.getRuntime().maxMemory();
                int cacheSize = (int) (maxMemory / 8);
                playManager.lruCache = new LruCache<String, Bitmap>(cacheSize) {
                    @Override
                    protected int sizeOf(String key, Bitmap value) {
                        return value.getByteCount();
                    }
                };
                playManager.videoInfoHashMap = new HashMap<>();
            }
        }
        return playManager;
    }

    public void init() {
        //创建视频播放器和弹幕
        playManager.myVideoView = new MyVideoView(BaseApplication.Companion.getInstance());
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ScreenUtilKt.screenWidth(), ScreenUtilKt.screenHeight());
        myVideoView.setLayoutParams(layoutParams);
    }

    /**
     * 判断当前播放item是否彻底都划走消失
     *
     * @param url
     */
    public void onDetach(String url) {
        LogUtilKt.logDebug("usingInfo onDetach");
        //切换视频后 清空当前在播放视频信息
        if (usingInfo != null && url.equals(usingInfo.getVideoUrl())) {
            usingInfo = null;
        }
    }

    /**
     * 只显示封面图片 账号被挤占下线时展示
     */
    public void onlyShowImage(){
        PlayManager.getInstance().stopPlay();
        PlayManager.getInstance().getMyVideoView().getBinding().videoThumb.setVisibility(View.VISIBLE);
        PlayManager.getInstance().getMyVideoView().getBinding().videoThumb.setImageBitmap(getBitmap(usingInfo.getVideoUrl()));
        LiveDataSet.showItem.postValue(true);
    }

    /**
     * 在播放url与新的url相同  不作处理
     *
     * @param videoInfo
     * @return
     */
    public Boolean play(VideoInfo videoInfo) {
        //不会重复播放
        if (usingInfo != null && usingInfo.getVideoUrl().equals(videoInfo.getVideoUrl())) {
            LogUtilKt.logDebug("usingInfo url not equals video url");
            return false;
        } else {
            //开始切换新视频
            LogUtilKt.logDebug("start playing...");
            //停止播放
            myVideoView.stop();
            //隐藏播放器
            myVideoView.getBinding().tourVideo.setVisibility(View.INVISIBLE);
            if (myVideoView.getParent() != null) {
                //播放器移除父view
                ViewUtil.removeParent(myVideoView);
            }
            //播放新视频
            myVideoView.playVideo(videoInfo);
        }
        return true;
    }

    /**
     * 停止播放
     */
    public void stopPlay() {
        myVideoView.stop();
        myVideoView.getBinding().tourVideo.setVisibility(View.INVISIBLE);
        if (myVideoView.getParent() != null) {
            ViewUtil.removeParent(myVideoView);
        }
    }

    /**
     * 暂停
     */
    public void pause() {
        myVideoView.pause();
    }

    /**
     * 恢复
     * @param seek
     */
    public void resume(boolean seek) {
        myVideoView.resume();
    }


    /**
     * 发送弹幕 优先级以及是否发送至服务器
     *
     * @param dmItem
     * @param high
     * @param fromSelf 自己发的弹幕就发送至服务器并且添加
     */
    public void sendOneDanmu(DmItem dmItem, boolean high, boolean fromSelf) {
        //添加到列表
        myVideoView.dmItemList.add(dmItem);
        if (fromSelf) {
            //自己的弹幕立即添加
            myVideoView.sendDanmu(dmItem, high ? 10 : 0);
            new FakeRepository().sendBarrage(dmItem, new Continuation<BaseResult<Object>>() {
                @NonNull
                @Override
                public CoroutineContext getContext() {
                    return EmptyCoroutineContext.INSTANCE;
                }

                @Override
                public void resumeWith(@NonNull Object o) {

                }
            });
        }else {
            //socket的弹幕添加只加到临时列表
            synchronized (myVideoView.tempDmList){
                myVideoView.tempDmList.add(dmItem);
                myVideoView.refreshTempList(false);
                LogUtilKt.logDebug("tempDmList.add(dmItem):"+dmItem);
            }
        }
        //弹幕条数变化 通知
        LiveDataSet.danmuSizeChange.postValue(myVideoView.dmItemList.size());

    }

    /**
     * 默认添加弹幕并发送至服务器
     *
     * @param dmItem
     * @param high
     */
    public void sendOneDanmu(DmItem dmItem, boolean high) {
        sendOneDanmu(dmItem, high, true);
    }


    public MyVideoView getMyVideoView() {
        return myVideoView;
    }

    public Bitmap getBitmap(String tag) {
        return lruCache.get(tag);
    }

    public void saveBitmap(String tag, Bitmap bitmap) {
        lruCache.put(tag, bitmap);
    }

    public VideoInfo getVideoInfo(String tag) {
        return videoInfoHashMap.get(tag);
    }

    public void saveVideoInfo(VideoInfo info, String tag) {
        videoInfoHashMap.put(tag, info);
    }

    public void createVideoThumbnail(String url) {
        createVideoThumbnail(url, null,null,false);
    }

    /**
     * 请求视频封面 以及是否显示
     *
     * @param url
     * @param imageView
     * @param view 传进来的滑动列表的子view
     * @param init 是否是第一次加载初始化 包含自动播放
     */
    public void createVideoThumbnail(String url, ImageView imageView,View view,boolean init) {
        LogUtilKt.logDebug("createVideoThumbnail:" + url);
        Bitmap bitmap = null;
        //查看是否已经缓存
        bitmap = PlayManager.getInstance().getBitmap(url);
        //未缓存 开始获取
        if (bitmap == null) {
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            int kind = MediaStore.Video.Thumbnails.MINI_KIND;
            long durationTime = 0;
            int width = 0, height = 0;
            try {
                if (Build.VERSION.SDK_INT >= 14) {
                    retriever.setDataSource(url, new HashMap<String, String>());
                } else {
                    retriever.setDataSource(url);
                }
                //获取视频封面
                bitmap = retriever.getFrameAtTime();
                durationTime = Long.valueOf(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));//时长(毫秒)
                width = Integer.parseInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH));//宽
                height = Integer.parseInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT));//高
                VideoInfo temp = new VideoInfo(url, durationTime, width, height);
                //保存视频信息
                PlayManager.getInstance().saveVideoInfo(temp, url);
                //缓存封面
                PlayManager.getInstance().saveBitmap(url, bitmap);
            } catch (Exception ex) {
                // Assume this is a corrupt video file
                LogUtilKt.logDebug("create video thumbnail exception:" + ex);
            } finally {
                try {
                    retriever.release();
                } catch (RuntimeException ex) {
                    // Ignore failures while cleaning up.
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        LogUtilKt.logDebug("createVideoThumbnail11111:" + url);
        Bitmap finalBitmap = bitmap;
        //切换到ui线程更新ui
        MainExecutor.get().execute(() -> {
            //imageview不为空就显示出来
            if (imageView != null) {
                imageView.setVisibility(View.VISIBLE);
                imageView.setImageBitmap(finalBitmap);
                //第一次加载视频列表 自动播放第一个视频
                if (init){
                    LogUtilKt.logDebug("position == 0 && !PlayManager.getInstance().isInit");
                    PlayManager.getInstance().isInit = true;
                    //视频列表的第一个item初始化完成 可以开始播放了
                    LiveDataSet.zeroItemInit.postValue(view);
                }
            }
        });

    }



}
